import re
import json
import sys
import client  # 导入 client.py
import threading
import pymysql
from XM import *
from untitled_2 import *
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
import SparkPythondemo  # 导入修改后的大模型接口
from datetime import datetime, timedelta



# MySQL 数据库连接配置
db_config = {
    'host': '192.168.154.158',
    'user': 'root',
    'password': '123456',
    'database': 'ChatRoomDB',
    'port': 3306,
    'charset': 'utf8mb4'
}


class LoginWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_LoginWindow()
        self.ui.setupUi(self)



        # 设置无边框和背景透明
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)

        # 设置阴影效果
        self.shadow = QtWidgets.QGraphicsDropShadowEffect(self)
        self.shadow.setOffset(0, 0)
        self.shadow.setBlurRadius(15)
        self.shadow.setColor(QtCore.Qt.black)
        self.ui.frame.setGraphicsEffect(self.shadow)

        # 连接按钮点击事件
        self.ui.pushButton.clicked.connect(self.login_in)  # 登录按钮
        self.ui.pushButton_13.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(0))
        self.ui.pushButton_2.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(1))  # 跳转到注册界面
        self.ui.pushButton_5.clicked.connect(self.register)  # 注册按钮
        self.ui.pushButton_6.clicked.connect(self.open_reset_password_page)  # 忘记密码
        self.ui.pushButton_8.clicked.connect(self.check_account_email)  # 检查账号和邮箱
        self.ui.pushButton_9.clicked.connect(self.reset_password)  # 修改密码


        self.show()

    def open_reset_password_page(self):
        """跳转到忘记密码页面"""
        self.ui.stackedWidget.setCurrentIndex(2)  # 跳转到page_3

    def check_account_email(self):
        """检查账号和邮箱是否注册过"""
        account = self.ui.lineEdit_7.text()
        email = self.ui.lineEdit_8.text()

        # 检查账号和邮箱是否存在于数据库
        try:
            connection = pymysql.connect(**db_config)
            with connection.cursor() as cursor:
                sql = "SELECT * FROM users WHERE account = %s AND email = %s"
                cursor.execute(sql, (account, email))
                result = cursor.fetchone()

                if result:
                    # 匹配成功，跳转到修改密码页面
                    QMessageBox.information(self, "验证成功", "请设置新密码")
                    self.ui.stackedWidget.setCurrentIndex(3)  # 跳转到page_4
                else:
                    QMessageBox.warning(self, "验证失败", "账号或邮箱不正确，请重试！")
        except Exception as e:
            print("数据库连接失败：", e)
        finally:
            connection.close()

    def reset_password(self):
        """重置密码"""
        account = self.ui.lineEdit_7.text().strip()
        email = self.ui.lineEdit_8.text().strip()
        new_password = self.ui.lineEdit_9.text()
        confirm_password = self.ui.lineEdit_10.text()

        if new_password != confirm_password:
            QMessageBox.warning(self, "密码不一致", "两次输入的密码不一致！")
            return

        try:
            connection = pymysql.connect(**db_config)
            with connection.cursor() as cursor:
                sql_update = "UPDATE users SET password = %s WHERE account = %s AND email = %s"
                affected_rows = cursor.execute(sql_update, (new_password, account.lower(), email.lower()))
                connection.commit()

                if affected_rows > 0:
                    QMessageBox.information(self, "重置成功", "密码已重置，请重新登录！")
                    self.ui.stackedWidget.setCurrentIndex(0)
                else:
                    QMessageBox.warning(self, "重置失败", "账号或邮箱不正确，未找到对应记录！")

        except Exception as e:
            print("数据库连接失败：", e)
            QMessageBox.warning(self, "数据库错误", str(e))
        finally:
            connection.close()

    def login_in(self):
        account = self.ui.lineEdit.text()
        password = self.ui.lineEdit_2.text()

        try:
            connection = pymysql.connect(**db_config)
            with connection.cursor() as cursor:
                sql = "SELECT * FROM users WHERE account = %s AND password = %s"
                cursor.execute(sql, (account, password))
                result = cursor.fetchone()

                if result:
                    username = result[1]  # 假设用户名存储在 result 的第二列（根据你的数据库结构调整索引）
                    self.win = MainWindow(username)  # 将用户名传递给 MainWindow
                    self.win.show()  # 显示 MainWindow
                    self.close()  # 关闭登录窗口
                else:
                    QMessageBox.warning(self, "登录失败", "账号或密码错误！")
        except Exception as e:
            print("数据库连接失败：", e)
            QMessageBox.warning(self, "数据库错误", f"登录失败：{e}")
        finally:
            connection.close()


    def register(self):
        account = self.ui.lineEdit_3.text()
        username = self.ui.lineEdit_13.text()  # 新增用户名
        password = self.ui.lineEdit_4.text()
        confirm_password = self.ui.lineEdit_5.text()
        email = self.ui.lineEdit_6.text()

        if password != confirm_password:
            QMessageBox.warning(self, "注册失败", "两次输入的密码不一致！")
            return

        if "@" not in email or "." not in email:
            QMessageBox.warning(self, "注册失败", "请输入有效的邮箱地址！")
            return

        try:
            connection = pymysql.connect(**db_config)
            with connection.cursor() as cursor:
                sql_check = "SELECT * FROM users WHERE account = %s OR email = %s"
                cursor.execute(sql_check, (account, email))
                if cursor.fetchone():
                    QMessageBox.warning(self, "注册失败", "该账号或邮箱已被注册！")
                else:
                    sql_insert = "INSERT INTO users (account, username, password, email) VALUES (%s, %s, %s, %s)"
                    cursor.execute(sql_insert, (account, username, password, email))
                    connection.commit()
                    QMessageBox.information(self, "注册成功", "账号注册成功，请登录！")
                    self.ui.stackedWidget.setCurrentIndex(0)
        except Exception as e:
            print("数据库连接失败：", e)
        finally:
            connection.close()






class MainWindow(QMainWindow):
    def __init__(self,username):
        super().__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.username = username




        # 设置无边框和背景透明
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)

        # 设置阴影效果
        self.shadow = QtWidgets.QGraphicsDropShadowEffect(self)
        self.shadow.setOffset(0, 0)
        self.shadow.setBlurRadius(15)
        self.shadow.setColor(QtCore.Qt.black)
        self.ui.frame.setGraphicsEffect(self.shadow)


        # 登录后跳转至聊天界面
        self.ui.stackedWidget.setCurrentWidget(self.ui.page)

        # 设置只读
        self.ui.textEdit_2.setReadOnly(True)
        self.ui.textEdit_3.setReadOnly(True)

        #初始化评论数据
        self.comments = []  # 全局评论
        self.user_comments = {}  # 确保是字典类型，用于存储用户的独立评论

        # 加载评论数据
        self.load_user_comments_from_file()
        self.load_comments_from_file()

        # 显示初始评论
        self.display_user_comments()
        self.display_comments()

        # 连接按钮事件
        self.ui.pushButton_2.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page))
        self.ui.pushButton.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_2))
        self.ui.pushButton_5.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_3))
        self.ui.pushButton_7.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_4))
        self.ui.pushButton_8.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_5))

        # page_5子页面功能
        self.ui.pushButton_4.clicked.connect(lambda: self.ui.stackedWidget_2.setCurrentWidget(self.ui.page_6))
        self.ui.pushButton_10.clicked.connect(lambda: self.ui.stackedWidget_2.setCurrentWidget(self.ui.page_7))
        self.ui.pushButton_6.clicked.connect(lambda: self.ui.stackedWidget_2.setCurrentWidget(self.ui.page_8))

        # 连接发送按钮
        self.ui.pushButton_13.clicked.connect(self.send_message)
        self.ui.pushButton_14.clicked.connect(self.send_chat_message)
        self.ui.pushButton_15.clicked.connect(self.reply_to_comment)  # 评论回复按钮
        self.ui.pushButton_16.clicked.connect(self.request_match)  # 匹配按钮
        self.ui.pushButton_18.clicked.connect(self.update_user_info) #修改用户信息

        # 发布当前用户的评论按钮
        self.ui.pushButton_17.clicked.connect(self.publish_user_comment)

        # 连接服务器
        self.client_socket = client.connect_to_server()  # 连接 client.py 中的服务器
        if self.client_socket:
            self.start_receiving_thread()

        self.last_message_time = None

        self.show()




    #page_6功能实现




















    # page_3,page_7的功能实现
    # 发布当前用户的评论
    def publish_user_comment(self):
        comment_text = self.ui.textEdit_8.toPlainText().strip()
        if comment_text:
            # 在全局和用户评论文件中存储评论
            new_comment = [f"{self.username}: {comment_text}", []]
            self.comments.append(new_comment)  # 添加到全局评论
            self.user_comments.append(new_comment)  # 添加到当前用户评论

            # 更新显示
            self.display_comments()
            self.display_user_comments()

            # 保存到文件
            self.save_comments_to_file()  # 保存到全局文件
            self.save_user_comments_to_file()  # 保存到用户文件
            self.ui.textEdit_8.clear()  # 清空输入框

    # 在 page_3 上显示所有用户的评论
    def display_comments(self):
        all_comments_text = ""
        for comment, replies in self.comments:
            all_comments_text += f"{comment}\n"
            for reply in replies:
                all_comments_text += f"  回复: {reply}\n"
            all_comments_text += "\n"
        self.ui.textEdit_5.setPlainText(all_comments_text)


    # 在 page_7 上显示当前用户的评论及他人回复
    def display_user_comments(self):
        user_comments_text = ""

        # 遍历当前用户的评论
        for user_comment, user_replies in self.user_comments:
            user_comments_text += f"{user_comment}\n"

            # 显示当前用户的回复
            for reply in user_replies:
                user_comments_text += f"  回复: {reply}\n"

            # 查找别人对当前用户评论的回复
            for comment, replies in self.comments:
                if comment == user_comment:
                    for reply in replies:
                        if reply not in user_replies:  # 排除当前用户自己添加的回复
                            user_comments_text += f"  他人回复: {reply}\n"

            user_comments_text += "\n"

        self.ui.textEdit_9.setPlainText(user_comments_text)

    # 回复评论（在 page_3 上输入回复并同步到当前用户的视图）
    def reply_to_comment(self):
        input_text = self.ui.textEdit_6.toPlainText().strip()
        match = re.match(r"^用户(\d+)\s(.+)$", input_text)

        if match:
            comment_index = int(match.group(1)) - 1
            reply_text = match.group(2).strip()

            if 0 <= comment_index < len(self.comments):
                # 添加回复到全局评论
                self.comments[comment_index][1].append(reply_text)
                self.display_comments()
                self.save_comments_to_file()

                # 检查是否是当前用户的评论
                if comment_index < len(self.user_comments):
                    self.user_comments[comment_index][1].append(reply_text)
                    self.display_user_comments()
                    self.save_user_comments_to_file()

                self.ui.textEdit_6.clear()  # 清空输入框
            else:
                self.ui.textEdit_6.setPlainText("无效的用户编号，请检查输入")
        else:
            self.ui.textEdit_6.setPlainText("请在格式“用户X 回复内容”中输入")

    # 保存所有评论和回复到全局文件
    def save_comments_to_file(self, filename="comments.json"):
        try:
            with open(filename, "w", encoding="utf-8") as file:
                json.dump(self.comments, file, ensure_ascii=False, indent=4)
        except Exception as e:
            print(f"保存评论时出错: {e}")

    # # 保存当前用户的评论和回复到用户文件
    # def save_user_comments_to_file(self, filename="user_comments.json"):
    #     try:
    #         with open(filename, "w", encoding="utf-8") as file:
    #             user_data = {self.username: self.user_comments}
    #             json.dump(user_data, file, ensure_ascii=False, indent=4)
    #     except Exception as e:
    #         print(f"保存用户评论时出错: {e}")

    def save_user_comments_to_file(self, filename="user_comments.json"):
        try:
            # Load existing data if available
            try:
                with open(filename, "r", encoding="utf-8") as file:
                    all_users_data = json.load(file)
            except (FileNotFoundError, json.JSONDecodeError):
                all_users_data = {}  # If file doesn't exist or is empty, initialize a new dictionary

            # Update the current user's comments
            all_users_data[self.username] = self.user_comments

            # Save all users' comments back to the file
            with open(filename, "w", encoding="utf-8") as file:
                json.dump(all_users_data, file, ensure_ascii=False, indent=4)
        except Exception as e:
            print(f"保存用户评论时出错: {e}")

    # 从文件加载当前用户的评论和回复
    def load_user_comments_from_file(self, filename="user_comments.json"):
        try:
            with open(filename, "r", encoding="utf-8") as file:
                all_users_data = json.load(file)
                # Load comments for the current user only
                self.user_comments = all_users_data.get(self.username, [])
                self.display_user_comments()  # Display the current user's comments
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"加载用户评论时出错: {e}")
            self.user_comments = []


    def load_comments_from_file(self, filename="comments.json"):
        """从文件加载评论和回复"""
        try:
            with open(filename, "r", encoding="utf-8") as file:
                self.comments = json.load(file)
                self.display_comments()  # 加载后立即显示
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"加载评论时出错: {e}")
            self.comments = []  # 如果文件不存在或解析出错，则初始化为空











    # page_2的功能实现
    def request_match(self):
        """发送匹配请求到服务器"""
        try:
            self.client_socket.send("/match_request".encode('utf-8'))
            self.ui.textEdit_3.append("匹配请求已发送，正在寻找相似用户...")
        except:
            self.ui.textEdit_3.append("发送匹配请求失败。")

    def receive_messages(self):
        """从服务器接收消息并显示"""
        while True:
            try:
                message = self.client_socket.recv(1024).decode('utf-8')
                if message:
                    self.ui.textEdit_3.append(message)
                else:
                    break
            except:
                self.ui.textEdit_3.append("连接到服务器失败。")
                break

    def start_receiving_thread(self):
        """启动接收服务器消息的线程"""
        self.receiving_thread = threading.Thread(target=self.receive_messages)
        self.receiving_thread.daemon = True
        self.receiving_thread.start()

    # 将发送和接收消息的代码与服务器交互逻辑进行整合。
    def send_chat_message(self):
        """从 textEdit_4 获取输入并发送消息到服务器"""
        message = self.ui.textEdit_4.toPlainText().strip()
        if message:
            try:
                self.client_socket.send(message.encode('utf-8'))
                self.ui.textEdit_3.append(f"我: {message}")
                self.ui.textEdit_4.clear()
            except:
                self.ui.textEdit_3.append("消息发送失败。")

    def closeEvent(self, event):
        """关闭窗口时关闭套接字"""
        if self.client_socket:
            self.client_socket.close()
        event.accept()








    #page_8的功能实现
    def update_user_info(self):
        """更新用户信息"""
        new_username = self.ui.lineEdit_7.text().strip()  # 获取新的用户名
        new_account = self.ui.lineEdit_10.text().strip()  # 获取新的账号
        new_password = self.ui.lineEdit_8.text().strip()  # 获取新的密码
        new_email = self.ui.lineEdit_9.text().strip()  # 获取新的邮箱

        # 检查信息是否为空
        if not new_username or not new_account or not new_password or not new_email:
            QMessageBox.warning(self, "更新失败", "所有字段都必须填写！")
            return

        # 检查邮箱格式
        if "@" not in new_email or "." not in new_email:
            QMessageBox.warning(self, "更新失败", "请输入有效的邮箱地址！")
            return

        try:
            # 连接到数据库并更新用户信息
            connection = pymysql.connect(**db_config)
            with connection.cursor() as cursor:
                # 更新用户信息 SQL 查询
                sql_update = """
                    UPDATE users
                    SET username = %s, password = %s, email = %s
                    WHERE account = %s
                """
                cursor.execute(sql_update, (new_username, new_password, new_email, new_account))
                connection.commit()

                if cursor.rowcount > 0:
                    QMessageBox.information(self, "更新成功", "用户信息已更新！")
                else:
                    QMessageBox.warning(self, "更新失败", "没有找到匹配的账号，请检查账号信息！")
        except Exception as e:
            QMessageBox.warning(self, "数据库错误", f"更新失败：{e}")
            print(f"数据库连接失败：{e}")
        finally:
            connection.close()





















    #page_4的功能实现
    def send_message(self):
        """发送消息到聊天框并获取大模型回复"""
        input_text = self.ui.textEdit.toPlainText().strip()

        if input_text:
            current_time = datetime.now()
            show_time = False

            # 判断是否显示时间戳
            if self.last_message_time is None or (current_time - self.last_message_time) > timedelta(minutes=5):
                show_time = True
                self.last_message_time = current_time

            # 显示用户输入
            current_text = self.ui.textEdit_2.toPlainText()
            if show_time:
                new_text = f"{current_text}\n[{current_time.strftime('%Y-%m-%d %H:%M:%S')}]\n用户: {input_text}"
            else:
                new_text = f"{current_text}\n用户: {input_text}"

            self.ui.textEdit_2.setPlainText(new_text)

            # 调用大模型接口获取回复
            response = SparkPythondemo.get_response(input_text)
            response_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            # 显示大模型的回复
            new_text = f"{new_text}\n小爱同学: {response}"
            self.ui.textEdit_2.setPlainText(new_text)

            # 滚动到文本框底部
            self.ui.textEdit_2.verticalScrollBar().setValue(self.ui.textEdit_2.verticalScrollBar().maximum())

            # 清空输入框
            self.ui.textEdit.clear()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    win = LoginWindow()
    sys.exit(app.exec_())

